package labox.innovation.db;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import labox.innovation.config.Config;
import labox.innovation.db.core.HeapByteBuffer;
import labox.innovation.db.core.SqlData;
import labox.innovation.db.manager.DBConnetionStateManager;
import labox.innovation.db.proxy.ConnectionProxy;
import labox.innovation.db.proxy.PreparedStatementProxy;
import labox.innovation.db.util.DbUtil;
import labox.innovation.db.util.SqlDataIdFactory;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance.PlayerQuestValues;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PlayerQuest {
	public static final Logger _log = LoggerFactory.getLogger(PlayerQuest.class.getName());
	/**
	 * ���½�ɫ����
	 */
	private static final String UPDATE_CHARACTER_QUEST = "REPLACE INTO character_quests (charId,details) VALUES(?,?)";
	/**
	 * ���ؽ�ɫ����
	 */
	private static final String LOAD_CHARACTER_QUEST = "SELECT charId,details from character_quests where charId=?";
	/**
	 * ɾ���ɫ����
	 */
	public static final String PHYSICAL_DELETE_QUESTS_BY_OWNERID="delete from character_quests where charId=?";
	/**
	 * ������������
	 * 
	 * @param player
	 * @throws SQLException 
	 */
	public static void storeQuest(FuzePcInstance player) {
		ConnectionProxy con = null;
		PreparedStatementProxy ptmt = null;
		SqlData data = null;
		Object[] params = null;
		HeapByteBuffer _buf = HeapByteBuffer.newInstance();
		_buf.clear();
		_buf.writeInt(player.getQuestValues().size());
		for (PlayerQuestValues playerQuestValues : player.getQuestValues()) {
			_buf.writeString(playerQuestValues.getName());
			_buf.writeString(playerQuestValues.getVal());
			_buf.writeString(playerQuestValues.getValue());
		}
		_buf.flip();
		try {
			if (!DBConnetionStateManager.getDbState()) {
				params = new Object[] { player.getObjectId(), _buf };
				data = new SqlData(SqlDataIdFactory.createSqlId("character_quests", player.getObjectId()), UPDATE_CHARACTER_QUEST, params);
				DBConnetionStateManager.addDbTask(data);
			} else {
				con = ConnectionProxy.newInstance();
				if (con != null)
					ptmt = con.prepareStatement(UPDATE_CHARACTER_QUEST);
				if (DbUtil.isDbNormal(DBConnetionStateManager.getDbState(), con, ptmt)) {
					ptmt.setLong(1, player.getObjectId());
					ptmt.setBinaryStream(2, _buf, _buf.limit());
					int rs = ptmt.executeUpdate();
					if (rs != PreparedStatementProxy.NETWORKDISCONNECTION) {
						HeapByteBuffer.recycle(_buf);
					} else {
						params = new Object[] { player.getObjectId(), _buf };
						data = new SqlData(SqlDataIdFactory.createSqlId("character_quests", player.getObjectId()), UPDATE_CHARACTER_QUEST, params);
						DBConnetionStateManager.addDbTask(data);
					}
				}else{
					params = new Object[] { player.getObjectId(), _buf };
					data = new SqlData(SqlDataIdFactory.createSqlId("character_quests", player.getObjectId()), UPDATE_CHARACTER_QUEST, params);
					DBConnetionStateManager.addDbTask(data);
				}
			}

		} catch (SQLException e) {
			_log.error("save character quest eror", Config.SERVER_ID, e);
			e.printStackTrace();
		} finally {
			if (ptmt != null)
				ptmt.close();
			if (con != null)
				con.close();
		}
	}

	/**
	 * ���ؽ�ɫ����
	 * 
	 * @param player
	 */
	public static void restoreQuest(FuzePcInstance player) {
		ConnectionProxy con = null;
		PreparedStatementProxy ptmt = null;
		ResultSet res = null;
		HeapByteBuffer _buf = HeapByteBuffer.newInstance();
		try {
			if (!DBConnetionStateManager.getDbState())
				return;
			con = ConnectionProxy.newInstance();
			if (con != null)
				ptmt = con.prepareStatement(LOAD_CHARACTER_QUEST);
			if (!DbUtil.isDbNormal(DBConnetionStateManager.getDbState(), con, ptmt))
				return;
			ptmt.setLong(1, player.getObjectId());
			res = ptmt.executeQuery();
			if (res == null)
				return;
			String name;
			String val;
			String value;
			byte[] bytes;
			List<PlayerQuestValues> _questValues = new ArrayList<PlayerQuestValues>();
			while (res.next()) {
				_buf.clear();
				bytes = res.getBytes("details");
				_buf.write(bytes, 0, bytes.length);
				_buf.flip();
				int size = _buf.readInt();
				player.getQuestValues().clear();
				for (int i = 0; i < size; i++) {
					name = _buf.readString();
					val = _buf.readString();
					value = _buf.readString();
					PlayerQuestValues playerQuestValues = new PlayerQuestValues(name, val, value);
					_questValues.add(playerQuestValues);
				}
				player.setQuestValues(_questValues);
			}
		} catch (Exception e) {
			_log.error("Erorr PlayerQuest restoreQuest", Config.SERVER_ID, e);
			e.printStackTrace();
		} finally {
			HeapByteBuffer.recycle(_buf);
			if (res != null)
				try {
					res.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			if (ptmt != null)
				ptmt.close();
			if (con != null)
				con.close();
		}
	}
}
